package com.dfiov.cloud.msmtools.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JsonUtil {

	public static <T> List<T> jsonListOperation(String content, String entityName, Class<T> bean) {
		// 获取上层Json
		JSONObject result = JSON.parseObject(content + "", JSONObject.class);
		Object embeddedArray = result.get("_embedded");
		result = JSON.parseObject(embeddedArray + "", JSONObject.class);

		// 获取List
		Object jsonObj = result.get(entityName);
		List<T> resultList = JSON.parseArray(jsonObj + "", bean);
		return resultList;
	}

	public static <T> T jsonToObject(String content, Class<T> bean) {
		// 获取上层Json
		T result = JSON.parseObject(content, bean);
		return result;
	}

	public static <T> List<T> jsonToList(String content, String entityName, Class<T> bean) {
		// 获取上层Json
		JSONObject result = JSON.parseObject(content + "", JSONObject.class);
		// 获取List
		Object jsonObj = result.get(entityName);
		List<T> resultList = JSON.parseArray(jsonObj + "", bean);
		return resultList;
	}

	public static <T> List<T> jsonToList(String json, Class<T> bean) {
		// 获取上层Json
		List<T> resultList = JSON.parseArray(json, bean);
		return resultList;
	}

	public static String objToJsonStr(Object object) {
		return JSON.toJSONString(object);
	}

	public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {
		if (mainNode == null)
			return updateNode;
		Iterator<String> fieldNames = updateNode.fieldNames();
		while (fieldNames.hasNext()) {

			String fieldName = fieldNames.next();
			JsonNode jsonNode = mainNode.get(fieldName);

			if (jsonNode != null) {
				if (jsonNode.isObject()) {
					merge(jsonNode, updateNode.get(fieldName));
				} else if (jsonNode.isArray()) {
					for (int i = 0; i < jsonNode.size(); i++) {
						merge(jsonNode.get(i), updateNode.get(fieldName).get(i));
					}
				}
			} else {
				if (mainNode instanceof ObjectNode) {
					// Overwrite field
					JsonNode value = updateNode.get(fieldName);

					if (value.isNull()) {
						continue;
					}
					if (value.isIntegralNumber() && value.toString().equals("0")) {
						continue;
					}
					if (value.isFloatingPointNumber() && value.toString().equals("0.0")) {
						continue;
					}
					((ObjectNode) mainNode).put(fieldName, value);
				}
			}
		}
		return mainNode;
	}

	public static String mergeResult(LinkedHashMap<String, Object> reqParam) {
		JsonNode mainNode = null;
		for (Map.Entry<String, Object> resultMap : reqParam.entrySet()) {
			Object v = resultMap.getValue();
			if (v instanceof JsonNode) {
				mainNode = merge(mainNode, (JsonNode) v);
			}
		}
		return mainNode.toString();
	}
}
